﻿#include "qglobalconfig.h"
#include <QCoreApplication>
#include <QDir>
#include <QStandardPaths>
#include <QDebug>


QMutex QGlobalConfig::mutex;
QGlobalConfig* QGlobalConfig::instance = nullptr;

QGlobalConfig &QGlobalConfig::getInstance()
{
    if (instance == nullptr) {
        QMutexLocker locker(&mutex);
        if (instance == nullptr) {
            instance = new QGlobalConfig();
        }
    }
    return *instance;
}

void QGlobalConfig::deleteInstance()
{
    if (instance != nullptr) {
        delete instance;
        instance = nullptr;
    }
}

void QGlobalConfig::init(QString configPath, QMap<QString, QVariant> defaultSettings)
{
    QWriteLocker locker(&m_lock);  // 获取写锁
//    qDebug() << __FUNCTION__ << isInit;
    if(!isInit){
//        QDir().mkpath(configPath);  // 确保目录存在
//        qDebug() << __FUNCTION__ << configPath;
        // 初始化QSettings
        settings = new QSettings(configPath, QSettings::IniFormat);
        settings->setIniCodec("UTF-8");
        isInit = true;
        for(QMap<QString,QVariant>::iterator it = defaultSettings.begin();it != defaultSettings.end();it++){
            if(settings->value(it.key()).isNull()) settings->setValue(it.key(),it.value());
        }
    }

    // 获取所有的顶级组（如果有的话）
    QStringList groups = settings->childGroups();
    for (const QString &group : qAsConst(groups)) {
        settings->beginGroup(group);
        // 遍历当前组中的所有键
        QStringList keys = settings->childKeys();
        for (const QString &key : qAsConst(keys)) {
            settingsMap[group + "/" + key] = settings->value(key);
        }
        settings->endGroup();
    }

    // 如果没有组，则直接获取顶层的所有键
    if (groups.isEmpty()) {
        QStringList keys = settings->allKeys();
        for (const QString &key : qAsConst(keys)) {
            settingsMap[key] = settings->value(key);
        }
    }
}

void QGlobalConfig::uninit()
{
    QWriteLocker locker(&m_lock);  // 获取写锁
    qDebug() << __FUNCTION__ << isInit;
    if(isInit){
        for(QMap<QString,QVariant>::iterator it = settingsMap.begin();it != settingsMap.end();it++){
//            qDebug() << __FUNCTION__ << "save config:"<< it.key() << "=" <<it.value();
            settings->setValue(it.key(),it.value());
        }
        delete settings;
        isInit = false;
    }
}
// 构造函数
QGlobalConfig::QGlobalConfig() {
    isInit = false;
    // 获取应用程序名
//    QString appName = QCoreApplication::applicationName();
//    // 生成配置文件路径
//    //QString configPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
//    QString configPath = QCoreApplication::applicationDirPath();
//    QDir().mkpath(configPath);  // 确保目录存在
//    QString configFilePath = configPath + "/" + appName + ".ini";
}
// 析构函数
QGlobalConfig::~QGlobalConfig()
{
    uninit();
}

void QGlobalConfig::write(const QString &group, const QString &key, const QVariant &value)
{
    QWriteLocker locker(&m_lock);  // 获取写锁

    settingsMap[group+"/"+key] = value;
//    settings->beginGroup(group);
//    settings->setValue(key, value);
//    settings->endGroup();
}

void QGlobalConfig::write(const QString &key, const QVariant &value)
{
    QWriteLocker locker(&m_lock);  // 获取写锁

    settingsMap[key] = value;
//    settings->setValue(key, value);
}

// 读取配置
QVariant QGlobalConfig::read(const QString &group, const QString &key, const QVariant &defaultValue)
{
    QReadLocker locker(&m_lock);  // 获取读锁
    QVariant value;
    QMap<QString,QVariant>::const_iterator it= settingsMap.find(group+"/"+key);
    if( it == settingsMap.end()){
        settings->beginGroup(group);
        value = settings->value(key, defaultValue);
        settings->endGroup();
        settingsMap[group+"/"+key] = value;
    }else{
        value = it.value();
    }
    return value;
}

QVariant QGlobalConfig::read(const QString &key, const QVariant &defaultValue)
{
    QReadLocker locker(&m_lock);  // 获取读锁
    QVariant value;
    QMap<QString,QVariant>::const_iterator it= settingsMap.find(key);
    if(it == settingsMap.end()){
        value = settings->value(key, defaultValue);
        settingsMap[key] = value;
    }else{
        value = it.value();
    }
    return value;
}

// 移除指定键
void QGlobalConfig::remove(const QString &group, const QString &key)
{
    QWriteLocker locker(&m_lock);  // 获取写锁

    settingsMap.remove(group+"/"+key);

    settings->beginGroup(group);
    settings->remove(key);
    settings->endGroup();
}

void QGlobalConfig::remove(const QString &key)
{
    QWriteLocker locker(&m_lock);  // 获取写锁

    settingsMap.remove(key);
    settings->remove(key);
}

// 清空所有配置
void QGlobalConfig::clear()
{
    QWriteLocker locker(&m_lock);  // 获取写锁
    settingsMap.clear();
    settings->clear();
}

void QGlobalConfig::push()
{
    QWriteLocker locker(&m_lock);  // 获取写锁

    if(isInit){
        settings->endGroup();
        for(QMap<QString,QVariant>::iterator it = settingsMap.begin();it != settingsMap.end();it++){
            settings->setValue(it.key(),it.value());
        }
    }
}
